/**
 * 路由跳转监听
 */

import nprogress from "nprogress";
import { default as router } from "./router";
import { AnyRoute } from "./router/base";
import { app_title, WHITE_LIST } from "./setting";
import { useMenuStore } from "./stores/menu";
import { useUserStore } from "./stores/user";

function getTitle(t) {
  if (t) {
    return `${t}-${app_title}`;
  }
  return app_title;
}

router.beforeEach(async (to, from, next) => {
  // start progress bar
  console.log(to);
  nprogress.start();
  // set page title
  document.title = getTitle(to.meta.title);

  // console.log("[ to ] >", to);
  const userStore = useUserStore();
  const menuStore = useMenuStore();
  if (WHITE_LIST.indexOf(to.path) !== -1) {
    next();
    nprogress.done();
  } else {
    try {
      const userinfo = await userStore.checkToken();

      if (menuStore.accessMenus.length == 0) {
        await menuStore.generateRoutes(userinfo.role);
        menuStore.accessMenus.forEach((item) => {
          router.addRoute(item);
        });
        router.addRoute(AnyRoute);

        next({ ...to, replace: true });
      } else {
        next();
      }

      nprogress.done();
    } catch (error) {
      console.log(error);
      next({ name: "login", query: { callback: to.path } });
      nprogress.done();
    }
  }
});
router.afterEach(() => {
  // NextLoading.done();
  nprogress.done();
});
router.onError((e) => {
  console.log("[ error router ] >", e);
});
